<template>
  <div class="upload-container" style="max-width: 200px;display: inline-block;">
    <!--    <el-button icon='el-icon-document' size="mini" :style="{background:color,borderColor:color}"-->
    <!--               @click="handleShowDrawer" type="primary">AI助手-->
    <!--    </el-button>-->
    <span title="AI助手" @click="handleShowDrawer"><svg-icon icon-class="ai-robot" style="font-size: 20px;" /> </span>
    <el-drawer
      title="AI助手(不支持连续对话)"
      :visible.sync="dialogVisible"
      :append-to-body="true"
      :wrapper-closable="true"
      size="1200px"
      direction="rtl"
      @open="handleOpend"
      @close="handleClose"
    >
      <div style="height: auto; display: flex; flex-direction: column;">
        <el-container>
          <el-main ref="messageList" style="padding-bottom: 300px; max-height: 600px; overflow-y: auto;">
            <el-tabs v-model="messageactiveName">
              <el-tab-pane label="当前消息" name="first">
                <!-- Check if there's original content -->
                <div v-if="originalContent !== ''">
                  <div class="message-block">
                    <div class="prompt-message">
                      <div class="message-body">
                        <div>原始内容:</div>
                      </div>
                    </div>
                    <div class="content-message">
                      <div class="message-body">
                        <!-- Display the original content -->
                        <div class="original-message" v-html="originalContent" />
                      </div>
                    </div>
                  </div>
                </div>
                <!-- Check if AI content is available -->
                <div v-if="content !== ''">
                  <div class="message-block">
                    <div class="prompt-message">
                      <div v-if="originalContent !== ''" class="message-body">
                        <div>AI 优化后的内容:</div>
                      </div>
                      <div v-else class="message-body">
                        <div>AI:</div>
                      </div>
                    </div>
                    <div class="content-message">
                      <div class="message-body">
                        <!-- Display the optimized content -->
                        <iframe ref="iframe" style="border: none;" :src="iframeSrc" width="100%" height="400" />
                      </div>
                    </div>
                  </div>
                </div>
              </el-tab-pane>
              <el-tab-pane label="历史消息" name="second">
                <div v-if="total" class="loading-more">{{ more_notice }}</div>
                <div v-for="msg in aicontents" v-if="msg" :key="msg.id" class="message-block">
                  <div class="prompt-message">
                    <div class="message-body">
                      <div>{{ msg.prompt }}</div>
                      <div class="message-time">{{ msg.create_at }}</div>
                    </div>
                  </div>
                  <div class="content-message">
                    <div class="message-body">
                      <div class="original-message" v-html="msg.content" />
                    </div>
                  </div>
                  <el-divider />
                </div>
              </el-tab-pane>
            </el-tabs>

          </el-main>
          <el-alert>
            {{ tips }}
          </el-alert>
          <el-footer style="position: fixed; bottom: 0px; height: 240px; padding-bottom: 50px;background-color: #FFF;">
            <el-row>
              <el-col>
                <el-select
                  v-model="aiprompt_id"
                  size="mini"
                  filterable
                  remote
                  reserve-keyword
                  placeholder="请输入关键词"
                  :remote-method="searchPrompts"
                  @change="handleInsertTemplate"
                >
                  <el-option value="" label="自定义" />
                  <el-option v-for="(item, index) in prompttempaltes" v-if="item" :key="index" :label="item.name" :value="item.id" />
                </el-select>
                <el-select v-model="engine" placeholder=" " size="mini" filterable clearable>
                  <el-option v-for="(item, index) in ai_engines" v-if="item && item.value" :key="`engine-${index}-${item.value}`" :label="item.label" :value="item.value" />
                </el-select>
                <el-button
                  style="width: 50px"
                  size="mini"
                  type="warning"
                  title="管理prompt"
                  icon="el-icon-setting"
                  @click="aipromptVisible = true"
                />
                <el-select v-model="app" size="mini" placeholder="应用于" class="head" filterable @change="handleGetPrompttempaltes">
                  <el-option
                    v-for="category in apps"
                    v-if="category"
                    :key="category.label"
                    :label="category.label"
                    :value="category.value"
                  />
                </el-select>
                <el-select v-model="all" size="mini" placeholder="选择种类" filterable @change="handleGetPrompttempaltes">
                  <el-option
                    label="所有"
                    value=""
                  />
                  <el-option
                    label="全公司"
                    value="company"
                  />
                  <el-option
                    label="我创建的"
                    value="mine"
                  />
                  <el-option
                    label="系统创建"
                    value="system"
                  />
                </el-select>
                <el-button
                  v-if="current_template.keywords && current_template.keywords.length"
                  style="width: 100px"
                  size="mini"
                  :type="hasNullKeywords ? 'danger':'success'"
                  title="shortcode"
                  icon="el-icon-setting"
                  @click="shortCodeVisible = true"
                >可变参数</el-button>
              </el-col>
            </el-row>
            <el-row style="padding-bottom: 30px">
              <el-col>
                <el-input v-model="user_prompt" type="textarea" :rows="8" :placeholder="placeholder" @focus="scrollToBottom" />
                <el-button v-if="content !== ''" type="primary" size="mini" @click="handInsert">插入</el-button>
                <el-button :loading="loading" type="primary" size="mini" @click="HandleGetContent">立即创建</el-button>
              </el-col>
            </el-row>
          </el-footer>
        </el-container>
      </div>
    </el-drawer>
    <aiprompt :is-visible="aipromptVisible" :app="app" @closeDialog="aipromptVisible=false" />
    <el-dialog
      title="配置参数"
      :visible.sync="shortCodeVisible"
      width="900px"
      append-to-body
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <el-alert>tips:系统会记住您输入的参数，再次使用请修改参数。</el-alert>
      <el-table :data="current_template.keywords || []" style="width: 100%">
        <el-table-column prop="code" label="参数" width="180" />
        <el-table-column label="值">
          <template slot-scope="scope">
            <el-input v-if="scope.row" v-model="scope.row.value" type="textarea" rows="2" size="mini" placeholder="值" />
          </template>
        </el-table-column>
        <el-table-column label="类型" width="200">
          <template slot-scope="scope">
            <el-select v-if="scope.row" v-model="scope.row.type" placeholder="类型">
              <el-option v-for="option in helpData" v-if="option" :key="option.type" :label="option.description" :value="option.type" />
            </el-select>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="100">
          <template slot-scope="scope">
            <el-button v-if="scope.row" size="mini" type="success" @click.prevent="removeSaveShortCode(scope.row)">保存</el-button>
          </template>
        </el-table-column>
      </el-table>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="handleSaveAlloptions">确 定</el-button>
      </span>
    </el-dialog>

  </div>

</template>

<script>
import Aiprompt from '../../views/cms/elements/aiprompt'
require('vue-select-image/dist/vue-select-image.css')
import Cookies from 'js-cookie'
import { Get as GetAiContent } from '@/api/cms/aicontent'
import { Get as GetAiPrompt } from '@/api/cms/aiprompt'
import { Post as PostShortCode } from '@/api/cms/shortcode'
import qs from 'qs'
import {
  Post
} from '@/api/cms/openai'
import { aiprompt_apps } from '../../api/crm/crmcommon'

export default {
  name: 'Aicontent',
  components: { Aiprompt },
  props: {
    color: {
      type: String,
      default: '#1890ff'
    },
    id: {
      type: String,
      default: ''
    },
    app: {
      type: String,
      default: ''
    },
    replace_data: {
      type: Object,
      default: () => {
        return {}
      }
    }
  },
  data() {
    return {
      originalContent: '', // Add this line
      placeholder: '告诉AI做什么',
      shortcodetemp: {
        code: '',
        value: '',
        type: 'mine'
      },
      helpData: [
        {
          type: 'mine',
          description: '个人数据'
        },
        {
          type: 'public',
          description: '公共数据'
        }
      ],
      shortCodeVisible: false,
      aipromptVisible: false,
      activeName: 0,
      more_notice: '滚动加载更多',
      aicontents: [],
      template_type: '写段落',
      aiprompt_id: '',
      tips: '',
      main_point: '',
      selected_content: '',
      dialogVisible: false,
      content: '',
      iframeSrc: '',
      user_prompt: '',
      prompt: '',
      engine: 'gpt-4o-mini',
      ai_engines: [
        {
          label: 'GPT-4o-mini',
          value: 'gpt-4o-mini'
        },
        {
          label: 'GPT-4o',
          value: 'gpt-4o'
        },
        {
          label: '通义千问',
          value: 'qwen_turbo'
        }
      ],
      all: '', // 'mine', 'system
      apps: aiprompt_apps || [],
      prompttempaltes: [],
      messageactiveName: 'first',
      currentResponseMsg: null,
      current_template: {
        keywords: []
      },
      loading: false,
      pagesize: 20,
      total: 0,
      page: 1
    }
  },
  computed: {
    replacedPrompt() {
      let result = this.prompt
      const replaceData = this.replace_data

      if (!result || !replaceData) return result

      Object.entries(replaceData).forEach(([key, value]) => {
        if (value != null) {
          const escapedKey = key.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
          const regex = new RegExp(`{{${escapedKey}}}`, 'g')
          result = result.replace(regex, value)
        }
      })

      return result
    },
    hasNullKeywords() {
      if (!this.current_template || !this.current_template.keywords) {
        return false
      }
      return this.current_template.keywords.some(item => item && item.value === '')
    }
  },
  watch: {
    // 监听id变化
    id: {
      handler(newVal) {
        if (this.dialogVisible) {
          this.handleContentUpdate()
        }
      }
    },
    // 监听replace_data变化
    replace_data: {
      handler(newVal) {
        this.updateTemplateKeywords()
      },
      deep: true
    },
    // 监听app变化
    app: {
      handler(newVal) {
        if (this.dialogVisible) {
          this.handleGetPrompttempaltes()
        }
      }
    },
    // 监听对话框显示状态
    dialogVisible: {
      handler(newVal) {
        if (newVal) {
          this.initializeData()
        }
      }
    }
  },
  created() {
    this.engine = Cookies.get('openai-engine') || 'gpt-4o-mini'
    this.aiprompt_id = Cookies.get('openai-aiprompt_id') || ''
    this.handleGetAiContent()
  },
  methods: {
    // 更新模板关键词
    updateTemplateKeywords() {
      if (this.current_template && this.current_template.keywords) {
        this.replaceKeywordValue(this.current_template.keywords, this.replace_data)
      }
    },

    // 防抖处理API请求
    debounceApiCall(fn, delay = 300) {
      const now = Date.now()
      if (now - this.lastUpdateTimestamp >= delay) {
        this.lastUpdateTimestamp = now
        fn()
      }
    },

    // 获取AI提示模板
    handleGetPrompttempaltes() {
      GetAiPrompt(null, qs.stringify({
        all: this.all,
        app: this.app,
        pagesize: this.pagesize,
        page: this.page
      }))
        .then(response => {
          this.prompttempaltes = (response.data.data || []).filter(item => !!item)
          // 去重和过滤 ai_engines
          const engines = (response.data.ai_engines || []).filter(item => !!item && item.value)
          this.ai_engines = engines.filter((item, index, self) =>
            index === self.findIndex(t => t.value === item.value)
          )
          this.updateTemplateKeywords()
        })
        .catch(error => {
          console.error('Failed to get prompt templates:', error)
          this.$message.error('获取提示模板失败')
        })
    },
    // 处理内容更新
    handleContentUpdate() {
      if (!this.id) {
        this.originalContent = ''
        this.content = ''
        return
      }

      const editor = window.tinymce && window.tinymce.get(this.id)
      if (!editor) return

      const content = editor.selection.getContent()
      if (content) {
        // 过滤HTML标签
        const cleanContent = content
          .replace(/<br>/g, '\n')
          .replace(/<p>/g, '')
          .replace(/<[^>]+>/g, '')

        this.originalContent = cleanContent
        this.replace_data['selected_content'] = cleanContent
        this.replace_data['all_content'] = editor.getContent()

        if (!this.prompt) {
          this.prompt = cleanContent
        }
      }

      // 延迟滚动到底部
      this.$nextTick(() => {
        setTimeout(this.scrollToBottom, 100)
      })
    },
    // 初始化数据
    initializeData() {
      this.handleGetAiContent()
      this.handleGetPrompttempaltes()
      this.handleContentUpdate()
    },
    scrollToBottom() {
      this.$nextTick(() => {
        const element = this.$refs.messageList
        if (element && element.$el) {
          element.$el.scrollTop = element.$el.scrollHeight
        }
      })
    },
    // 检查current_template.keywords中是否有空值
    checkKeywords() {
      if (!this.current_template || !this.current_template.keywords) {
        return true
      }
      return this.current_template.keywords.every(item => item && item.value !== '')
    },
    handleSaveAlloptions() {
      if (!this.current_template || !this.current_template.keywords) {
        this.shortCodeVisible = false
        return
      }

      let savedCount = 0
      const totalKeywords = this.current_template.keywords.length

      if (totalKeywords === 0) {
        this.shortCodeVisible = false
        return
      }

      for (const keyword of this.current_template.keywords) {
        if (!keyword) continue

        PostShortCode({
          code: keyword.code,
          value: keyword.value,
          type: keyword.type
        }).then(response => {
          this.replace_data[keyword.code] = keyword.value
          savedCount++
          if (savedCount === totalKeywords) {
            this.$message.success('所有关键词已成功保存')
            this.shortCodeVisible = false
          }
        }).catch(error => {
          this.$message.error(`保存关键词 "${keyword.code}" 时出错: ${error.message}`)
        })
      }
    },
    removeSaveShortCode(item) {
      if (!item) return
      this.shortcodetemp = item
      this.handleAddShortCode()
    },
    handleAddShortCode() {
      PostShortCode(this.shortcodetemp).then(response => {
        this.replace_data[this.shortcodetemp.code] = this.shortcodetemp.value
        // 提示成功
        this.$message.success('保存成功')
      })
    },
    searchPrompts(q) {
      GetAiPrompt(null, qs.stringify({
        all: this.all,
        kw: q,
        app: this.app,
        pagesize: this.pagesize,
        page: this.page
      }))
        .then(response => {
          this.prompttempaltes = (response.data.data || []).filter(item => !!item)
        })
    },
    handleGetAiContent() {
      GetAiContent(null, qs.stringify({
        pagesize: this.pagesize,
        aiprompt_id: this.aiprompt_id,
        page: this.page
      }))
        .then(response => {
          this.aicontents = (response.data.data || []).filter(item => !!item)
          this.total = response.data.total || 0
          // this.scrollToBottom()
        })
    },
    handleClose() {
      this.dialogVisible = false
      this.content = ''
      this.originalContent = ''
      this.user_prompt = ''
      this.current_template = { keywords: [] }
      this.aiprompt_id = ''
    },
    handleOpend() {
      if (this.id && window.tinymce) {
        const editor = window.tinymce.get(this.id)
        if (editor) {
          let content = editor.selection.getContent()
          if (content) {
            // 过滤掉所有html, br, p标签转化为换行符
            content = content.replace(/<br>/g, '\n')
            content = content.replace(/<p>/g, '')
            content = content.replace(/<[^>]+>/g, '')
            this.originalContent = content
            this.replace_data['selected_content'] = content
            this.replace_data['all_content'] = editor.getContent()
            // 如果prompot为空则使用选中的内容
            if (this.prompt === '') {
              this.prompt = content
            }
          }
        }
      } else {
        this.originalContent = ''
        this.content = ''
      }
      // 延迟1秒执行
      setTimeout(() => {
        this.scrollToBottom()
      }, 1000)
    },
    handleShowDrawer() {
      this.dialogVisible = true
      this.handleGetAiContent()
      this.handleGetPrompttempaltes()
    },
    replaceKeywordValue(keywords, replaceData) {
      if (!keywords || !Array.isArray(keywords) || !replaceData) return

      // 遍历每一个关键词
      keywords.forEach(keyword => {
        if (!keyword) return
        // 检查replaceData中是否存在与keyword的code相同的键
        if (replaceData.hasOwnProperty(keyword.code)) {
          // 如果存在，替换keyword的value为replaceData中相应的值
          keyword.value = replaceData[keyword.code]
        }
      })
    },
    handleInsertTemplate(value) {
      if (this.aiprompt_id !== '') {
        // 根据id发现模板
        this.current_template = this.prompttempaltes.find(item => item && item.id === value) || { keywords: [] }
        // 根据replace_data字段替换模板中的变量{{xx}}
        // let temp_prompt = this.current_template.prompt
        this.placeholder = this.current_template.placeholder || '告诉AI做什么'
        // 复制模板变量
        this.replaceKeywordValue(this.current_template.keywords, this.replace_data)
        if (this.current_template.keywords && this.current_template.keywords.length > 0) {
          this.shortCodeVisible = true
        }
        if (this.current_template.engine) {
          this.engine = this.current_template.engine
        }
      } else {
        this.prompt = ''
        this.current_template = { keywords: [] }
      }
      this.handleGetAiContent()
    },
    handleCopy(content) {
      navigator.clipboard.writeText(content).then(function() {
        this.$message.success('内容已经复制到剪切板')
      }, function() {
        this.$message.error('复制失败')
      })
    },
    HandleGetContent() {
      if (this.hasNullKeywords) {
        this.$message.error('请填写所有的关键词')
        this.shortCodeVisible = true
        return
      }
      this.loading = true
      this.content = ''
      // 检查内容
      if (this.checkKeywords() === false) {
        this.$message.error('请填写所有的关键词')
        this.loading = false
        this.shortCodeVisible = true
        return
      }
      // this.prompt = this.user_prompt
      this.content = ''
      Post({ prompt: this.user_prompt, engine: this.engine, aiprompt_id: this.aiprompt_id, keywords: this.current_template.keywords || [] })
        .then(response => {
          this.content = response.content
          const fullHtmlContent = `<!DOCTYPE html><html><body style="background-color: aliceblue;">${this.content}</body></html>`

          // 创建一个Blob对象，类型为"text/html"
          const blob = new Blob([fullHtmlContent], { type: 'text/html' })
          // 创建一个指向该Blob的URL
          this.iframeSrc = URL.createObjectURL(blob)
          this.loading = false
          Cookies.set('openai-engine', this.engine)
          Cookies.set('openai-aiprompt_id', this.aiprompt_id)
          navigator.clipboard.writeText(this.content).then(function() {
            this.$message.success('内容已经复制到剪切板')
          }, function() {
            this.$message.error('复制失败')
          })
          this.handleGetAiContent()
        }).catch(e => {
          console.log('error')
          this.loading = false
        }).finally(() => {
          // 使用$nextTick确保DOM已更新
          this.$nextTick(() => {
            this.scrollToBottom()
          })
        })
    },
    handInsert() {
      this.$emit('successCBK', { content: this.content })
      this.dialogVisible = false
    }
  }
}
</script>

<style scoped>
/* 消息容器样式 */
.message-container {
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
  font-family: Arial, sans-serif;
}

/* 当前消息样式 */
.current-message {
  background-color: #f0f0f0;
  border-radius: 8px;
  padding: 15px;
  margin-bottom: 20px;
}

/* 历史消息标签页样式 */
.history-tab {
  border-bottom: 1px solid #ddd;
  margin-bottom: 20px;
}

.history-tab button {
  background-color: #f8f8f8;
  border: none;
  padding: 10px 20px;
  cursor: pointer;
}

.history-tab button.active {
  background-color: #fff;
  border-bottom: 2px solid #007bff;
}

/* 原始消息源码样式 */
.original-message {
  background-color: #f8f8f8;
  border: 1px solid #e0e0e0;
  border-radius: 4px;
  padding: 15px;
  margin-bottom: 20px;
  font-family: 'Courier New', Courier, monospace;
  font-size: 14px;
  line-height: 1.4;
  white-space: pre-wrap;
  word-wrap: break-word;
  overflow-x: auto;
}

/* 优化标题样式 */
.original-message h1,
.original-message h2,
.original-message h3,
.original-message h4,
.original-message h5,
.original-message h6 {
  margin-top: 10px;
  margin-bottom: 5px;
  line-height: 1.2;
}

.original-message h1 { font-size: 20px; }
.original-message h2 { font-size: 18px; }
.original-message h3 { font-size: 16px; }
.original-message h4 { font-size: 15px; }
.original-message h5 { font-size: 14px; }
.original-message h6 { font-size: 13px; }

/* 优化段落样式 */
.original-message p {
  margin-top: 0;
  margin-bottom: 8px;
}

/* 代码块样式 */
.original-message pre {
  background-color: #f0f0f0;
  border: 1px solid #ddd;
  border-radius: 4px;
  padding: 10px;
  overflow-x: auto;
}

.original-message code {
  font-family: 'Courier New', Courier, monospace;
  font-size: 13px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .message-container {
    padding: 10px;
  }

  .current-message,
  .original-message {
    padding: 10px;
  }

  .original-message {
    font-size: 13px;
  }

  .original-message h1 { font-size: 18px; }
  .original-message h2 { font-size: 16px; }
  .original-message h3 { font-size: 15px; }
  .original-message h4 { font-size: 14px; }
  .original-message h5 { font-size: 13px; }
  .original-message h6 { font-size: 12px; }
}
i:hover {
        color: red;
    }
svg:hover {
        color: red;
    }
.el-textarea__inner {
  max-width: 1000px;
  /* 你还可以在这里添加其他样式 */
}
.message-block {
  margin-bottom: 3px; /* 每个消息块之间的间距 */
}

.message-time {
  font-size: 0.75rem;
  color: #999;
}
.prompt-message, .content-message {
  padding-left: 10px; /* 消息的内边距 */
  padding-right: 10px;
  background-color: #f5f5f5; /* 背景色 */
  border-radius: 4px; /* 边框圆角 */
  margin-bottom: 5px; /* prompt和content之间的间距 */
  word-wrap: break-word;
  white-space: pre-wrap; /* 保持格式化的空白字符，允许自动换行 */
}

.content-message {
  background-color: #fff; /* 为content设置白色背景 */
  margin-left: 20px;
}

.prompt-message {
  background-color: #e8f5e9; /* 为prompt设置稍微不同的背景色以区分 */
}
.message-body {
  word-wrap: break-word; /* 确保长文本能够自动换行 */
  margin-bottom: 2px;
}

el-container {
  display: flex;
  flex-direction: column;
  height: 100%; /* 根据需要调整 */
}

el-main {
  flex: 1;
  overflow-y: auto; /* 允许内容滚动 */
}

/* 需要调整footer样式以确保它在底部 */
el-footer {
  height: 240px; /* 根据实际高度调整 */
  line-height: 60px; /* 使内容垂直居中 */
  box-shadow: 0 -2px 4px rgba(0,0,0,0.1); /* 可选：添加阴影效果 */
}

</style>

